let network;
let allNodes = new vis.DataSet();
let allEdges = new vis.DataSet();
let currentSPOData = [];

// 初始化网络
function initNetwork() {
    const container = document.getElementById('network');
    const data = {
        nodes: allNodes,
        edges: allEdges
    };

    const options = {
        nodes: {
            shape: 'dot',
            size: 30,
            font: {
                size: 14,
                face: 'Microsoft YaHei'
            },
            borderWidth: 2,
            shadow: true
        },
        edges: {
            width: 2,
            shadow: true,
            arrows: {
                to: { enabled: true, scaleFactor: 1.2 }
            },
            font: {
                size: 12,
                align: 'middle'
            },
            smooth: {
                enabled: true,
                type: 'continuous'
            }
        },
        physics: {
            enabled: true,
            stabilization: {
                iterations: 100
            }
        },
        interaction: {
            hover: true,
            tooltipDelay: 100
        }
    };

    network = new vis.Network(container, data, options);

    network.on("click", function(params) {
        if (params.nodes.length > 0) {
            showNodeDetails(params.nodes[0]);
        } else if (params.edges.length > 0) {
            showEdgeDetails(params.edges[0]);
        }
    });
}

// 加载所有SPO数据
async function loadAllSPO() {
    updateStatus('正在加载SPO数据...', 'loading');

    try {
        const response = await fetch('http://127.0.0.1:6868/all');
        const data = await response.json();

        if (data.error) {
            throw new Error(data.error);
        }
        currentSPOData = data.spo_list || [];
        renderSPOTable(currentSPOData);
        updateStatus(`加载成功: ${data.count} 条SPO关系`, 'success');

    } catch (error) {
        console.error('Error loading SPO data:', error);
        updateStatus('加载失败: ' + error.message, 'error');
    }
}

// 加载可视化数据
async function loadVisualization() {
    updateStatus('正在加载可视化数据...', 'loading');

    try {
        const response = await fetch('http://127.0.0.1:6868/neo4j');
        const data = await response.json();
        if (data.error) {
            throw new Error(data.error);
        }
        allNodes.clear();
        allEdges.clear();
        allNodes.add(data.nodes);
        allEdges.add(data.edges);
        updateStatus(`可视化数据加载成功: ${data.count} 个节点`, 'success');
    } catch (error) {
        console.error('Error loading visualization data:', error);
        updateStatus('可视化加载失败: ' + error.message, 'error');
    }
}

// 加载元数据
async function loadMetadata() {
    updateStatus('正在加载元数据...', 'loading');

    try {
        const response = await fetch('http://127.0.0.1:6868/metadata');
        const data = await response.json();

        if (data.error) {
            throw new Error(data.error);
        }

        // 填充过滤器下拉框
        populateFilterDropdown('startLabelFilter', data.labels);
        populateFilterDropdown('endLabelFilter', data.labels);
        populateFilterDropdown('relTypeFilter', data.relationship_types);

        showInfoPanel('元数据信息', `
            <h4>数据库统计</h4>
            <p>节点总数: ${data.node_count}</p>
            <p>关系总数: ${data.relationship_count}</p>
            <h4>节点标签</h4>
            <p>${data.labels.join(', ')}</p>
            <h4>关系类型</h4>
            <p>${data.relationship_types.join(', ')}</p>
        `);

        updateStatus('元数据加载成功', 'success');

    } catch (error) {
        console.error('Error loading metadata:', error);
        updateStatus('元数据加载失败: ' + error.message, 'error');
    }
}

// 填充下拉框
function populateFilterDropdown(selectId, options) {
    const select = document.getElementById(selectId);
    // 清空现有选项（保留第一个选项）
    while (select.options.length > 1) {
        select.remove(1);
    }

    options.forEach(option => {
        const opt = document.createElement('option');
        opt.value = option;
        opt.textContent = option;
        select.appendChild(opt);
    });
}

// 应用过滤器
async function applyFilters() {
    const startLabel = document.getElementById('startLabelFilter').value;
    const relType = document.getElementById('relTypeFilter').value;
    const endLabel = document.getElementById('endLabelFilter').value;
    const searchTerm = document.getElementById('searchFilter').value;

    const params = new URLSearchParams();
    if (startLabel) params.append('start_label', startLabel);
    if (relType) params.append('rel_type', relType);
    if (endLabel) params.append('end_label', endLabel);
    if (searchTerm) params.append('search', searchTerm);

    updateStatus('正在应用过滤器...', 'loading');

    try {
        const response = await fetch(`http://127.0.0.1:6868/filter?${params}`);
        const data = await response.json();

        if (data.error) {
            throw new Error(data.error);
        }

        currentSPOData = data.spo_list || [];
        renderSPOTable(currentSPOData);
        updateStatus(`过滤结果: ${data.count} 条记录`, 'success');

    } catch (error) {
        console.error('Error applying filters:', error);
        updateStatus('过滤失败: ' + error.message, 'error');
    }
}

// 清除过滤器
function clearFilters() {
    document.getElementById('startLabelFilter').value = '';
    document.getElementById('relTypeFilter').value = '';
    document.getElementById('endLabelFilter').value = '';
    document.getElementById('searchFilter').value = '';
    loadAllSPO();
}

// 渲染SPO表格
function renderSPOTable(spoList) {
    const tableBody = document.getElementById('spoTableBody');
    const dataCount = document.getElementById('dataCount');

    tableBody.innerHTML = '';
    dataCount.textContent = `(${spoList.length} 条记录)`;
    spoList.forEach((spo, index) => {
        const row = document.createElement('tr');
        const startNode = spo.start;
        const endNode = spo.end;
        const relationship = spo.relationship;
        row.innerHTML = `
            <td style="text-align: center">
                <strong>${startNode.labels[0]}</strong><br>
                ${startNode.properties.name || '无名称'}
            </td>
            <td style="width: 100px;text-align: center">
                <strong>${relationship.type}</strong><br>
            </td>
            <td style="text-align: center">
                <strong>${endNode.labels[0]}</strong><br>
                ${endNode.properties.name || '无名称'}
            </td>
            <td style="width: 130px;text-align: center">
                <button class="btn-view" onclick="viewSPODetails(${index})">查看详情</button>
            </td>
        `;
        tableBody.appendChild(row);
    });
}

// 查看SPO详情
function viewSPODetails(index) {
    const spo = currentSPOData[index];
    showInfoPanel('SPO关系详情', `
        <h4>起始节点</h4>
        <div class="json-view">${JSON.stringify(spo.start, null, 2)}</div>
        
        <h4>关系</h4>
        <div class="json-view">${JSON.stringify(spo.relationship, null, 2)}</div>
        
        <h4>目标节点</h4>
        <div class="json-view">${JSON.stringify(spo.end, null, 2)}</div>
    `);
}

// 显示节点详情
function showNodeDetails(nodeId) {
    const node = allNodes.get(nodeId);
    if (node) {
        showInfoPanel('节点详情', `
            <h4>${node.label}</h4>
            <p><strong>类型:</strong> ${node.group}</p>
            <p><strong>ID:</strong> ${node.id}</p>
            <h4>属性:</h4>
            <div class="json-view">${JSON.stringify(node.properties, null, 2)}</div>
        `);
    }
}

// 显示边详情
function showEdgeDetails(edgeId) {
    const edge = allEdges.get(edgeId);
    if (edge) {
        showInfoPanel('关系详情', `
            <h4>${edge.label}</h4>
            <p><strong>从:</strong> ${allNodes.get(edge.from).label}</p>
            <p><strong>到:</strong> ${allNodes.get(edge.to).label}</p>
            <h4>属性:</h4>
            <div class="json-view">${JSON.stringify(edge.properties, null, 2)}</div>
        `);
    }
}

// 显示信息面板
function showInfoPanel(title, content) {
    const panel = document.getElementById('infoPanel');
    const panelContent = document.getElementById('panelContent');

    panelContent.innerHTML = content;
    panel.querySelector('h3').textContent = title;
    panel.style.display = 'block';
}

// 隐藏信息面板
function hideInfoPanel() {
    document.getElementById('infoPanel').style.display = 'none';
}

// 更新状态栏
function updateStatus(message, type = '') {
    const statusBar = document.getElementById('statusBar');
    statusBar.textContent = message;
    statusBar.className = 'status-bar ' + type;
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initNetwork();
    loadMetadata(); // 加载元数据来填充过滤器
    loadAllSPO()
    loadVisualization();
    updateStatus('就绪 - 点击按钮加载数据');
});